package com.huluobo.lc.kotlinim1807ak.contract.contract

import android.util.Log
import com.huluobo.lc.kotlinim1807ak.data.ContactListItem
import com.huluobo.lc.kotlinim1807ak.data.db.Contact
import com.huluobo.lc.kotlinim1807ak.data.db.IMDatabase
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread

/**
 * @author Lc
 * @description:
 * @date :2021/2/26 10:13
 */
class ContactPresenter(val view: ContactContact.View) : ContactContact.Presenter {
    val contactListItems = mutableListOf<ContactListItem>()//可变的list
    override fun loadContacts() {
        doAsync {
            //同步方法,可以用try catch来验证获取联系人成功或者失败
            try {
                //再次加载数据,清空集合
                contactListItems.clear()
                //清空数据库
                IMDatabase.instance.deleteAllContacts()

                val userNames = EMClient.getInstance().contactManager().allContactsFromServer
                userNames.sortBy { it[0] }
//                userNames.forEach {
//                    //拿到每一个联系人对象(名字,首字母)
//                    //it代表userNames中每一个String(用户名),it[0]代表首字母,toUpperCase代表转换为大写
//                    val contactListItem = ContactListItem(it, it[0].toUpperCase())
//                    contactListItems.add(contactListItem)
//                }
                userNames.forEachIndexed { index, s ->
                    //什么时候显示首字符,当index=0
                    //username上一位的首字符如果和当前首字符不同
                    val showFirstLetter = index == 0 || s[0] != userNames[index - 1][0]
                    val contactListItem = ContactListItem(s, s[0].toUpperCase(), showFirstLetter)
                    contactListItems.add(contactListItem)

                    val contact = Contact(mutableMapOf("name" to s))
                    IMDatabase.instance.saveContact(contact)
                }
                runOnUIThread { view.onLoadContactsSuccess() }
            } catch (e: HyphenateException) {
                runOnUIThread { view.onLoadContactsFailed() }
            }
        }
    }
}